package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import db.DBManager;

public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}
	
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Connection con = null;

		req.setCharacterEncoding("UTF-8");

		String password = req.getParameter("password");
		String user 	= req.getParameter("user");
				
		String msg = null;
		
		if((user == null || user.length() == 0) && 
				 (password == null 	|| password.length() == 0)){
			 msg = ("ユーザー名とパスワードを入力してください。");
		}
		else{
			con = DBManager.getConnection();
			
			String sql = "select * from useraccount where name = ?";
			
			try{
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setString(1, user);
				ResultSet rs = ps.executeQuery();
				
				if (rs.next()) {
					if (password.equals(rs.getString("password"))) {
						
						HttpSession session = req.getSession();
						session.setAttribute("user", user);
					}
					else {
						msg = "ユーザー名またはパスワードが間違っています。";
					}
				}
				else{
					msg = "ユーザー名またはパスワードが間違っています。";
				}
			}
			catch(SQLException e){
				e.printStackTrace();
			}
			
			String path = "/user.jsp";		
			if (msg != null) {
				path = "/Login.jsp";	
				req.setAttribute("msg", msg);
			}
			RequestDispatcher dispatcher = req.getRequestDispatcher(path);
			dispatcher.forward(req, resp);
		}
	}
}
